<template>
  <div class="cateBox">
    <teleport to=".header">
      <shopHeader center="search"/>
    </teleport>

    <!-- 左边导航 -->
    <van-sidebar v-model="active" class="bar" @change="switchHandler">
      <van-sidebar-item :class="{sidebar: active===index}" v-for="(item,index) in listLeft" :key="index" :title="item" />
    </van-sidebar>

    <div class="rightBox">
       <div class="right" v-for="(item,index) in goodsList" :key="index">
        <h3>{{ item.brand }}</h3>
        <div @click="$router.push({path: '/list', query: {keyword: item.brand }})" class="list" v-for="goods in item.goods" :key="goods.proid">
          <img :src="goods.img1">
          <p>￥{{ goods.originprice }}</p>
        </div>
      </div>
    </div>
   
    
  </div>
</template>
<script setup lang="ts">
import { getSideBar, getCateList, getBrandList} from '../../request/goods.ts'
import shopHeader from "../../components/header.vue"
import { ref, onMounted} from 'vue'

const active = ref<number>(0)
// 分类列表
const listLeft = ref<Array<string>>([])

const brandList = ref<{brand: string}[]>([])

interface goodsInfo{
  proid: string
  img1: string
  originprice: number
  [key: string]: any
}

interface GoodsList{
  cate?: string,
  brand?: string,
  goods?: Array<goodsInfo>
}

interface ReponseInfo{
  code?: string,
  data?: Array<string>
}

const goodsList = ref<Array<GoodsList>>([])

const getGoodsList = async () => {
  const res = await getCateList(listLeft.value[active.value])
  
  if ((res as ReponseInfo).code !== '200') return
  brandList.value = res.data

  brandList.value.forEach(async item =>{
    const resList = await getBrandList(listLeft.value[active.value], item.brand)
    if ((resList as unknown as goodsInfo).code !== '200') return
    goodsList.value.push({
      cate: listLeft.value[active.value],
      brand: item.brand,
      goods: resList.data
    })
  })
}

// 切换导航栏
const switchHandler = () => {
  goodsList.value = []
  getGoodsList()
}
onMounted(async () => {
  const barList = await getSideBar()
  if ((barList as ReponseInfo).code !== '200') return
  listLeft.value = barList.data.map((item: string) => item.trim())

  getGoodsList()
})


</script>
<style scoped lang="scss">
.van-sidebar-item--select:before{
  background-color: #ff0000;
}
.cateBox{
  width: 100%;
  height: 100%;
  display: flex;
  overflow: hidden;
  .bar{
    overflow: auto;
  }
  .rightBox{
    flex: 1;
    padding: 10px;
    overflow: auto;
  }
}
.list{
  display: inline-block;
  margin-bottom: 20px;
  text-align: center;
  margin-top: 10px;
  margin-right: 10px;
  img{
    width: 80px;
    height: 80px;
  }
  p{
    color: #ff0000;
    font-size: 18px;
  }
}
.sidebar{
  color: #ff0000;
}
</style>
